package com.originskyseed.platform.task.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.task.i18n.TaskResponseMsg;
import com.originskyseed.platform.task.model.SpreadLimit;
import com.originskyseed.platform.task.service.ISpreadLimitService;
import com.originskyseed.platform.task.vo.request.SpreadLimitRequestVO;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IFamilyService;
import com.originskyseed.platform.user.service.ITradeUnionService;
import com.originskyseed.platform.user.service.IUserInfoService;

/**
 * 推广上限记录表Controller类（OSI_SPREAD_LIMIT）
 *
 * @author wlj
 */
@Controller
@RequestMapping("/spreadLimit")
@BaseLocaleResource(localeFileName = "i18n_task")
public class SpreadLimitController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(SpreadLimitController.class);

    @DubboReference
    private ISpreadLimitService spreadLimitService;

    @DubboReference
    private IDeptService deptService;

    @DubboReference
    private IUserInfoService userInfoService;

    @DubboReference
    private IFamilyService familyService;

    @DubboReference
    private ITradeUnionService tradeUnionService;

    /**
     * 接单上限_分页查询
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/spreadLimitList.json", method = RequestMethod.POST)
    @RequiredParams(names = {"pageNo", "pageSize"})
    public BaseResponseBody<BasePage<SpreadLimit>> spreadLimitList(HttpServletRequest request) {
        BaseResponseBody<BasePage<SpreadLimit>> result = null;
        UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
        BasePage<SpreadLimit> page = null;
        // 请求对象
        SpreadLimitRequestVO requestVO = this.getParameterBean(SpreadLimitRequestVO.class);
        // Integer userType = userInfo.getType();//用户类型
        try {
            List<String> deptIdList = new ArrayList<>();
            Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId());
            if ((dept.getSourceSys() == 1 && dept.getType() == 3) || (dept.getSourceSys() == 2 && dept.getType() == 5)) { // 小组
                if (userInfo.getSourceSys() == 1) {
                    requestVO.setUserType(1);
                }
                deptIdList.add(userInfo.getDeptId());
            } else {
                this.selectDeptSon(dept.getCode(), deptIdList);
            }
            List<String> userIdList = new ArrayList<>();
            page = new BasePage<SpreadLimit>(requestVO.getPageNo(), requestVO.getPageSize());
            if (userInfo.getSourceSys() == 0) { // 运管--查询所有家族
                page = this.spreadLimitService.selectGroupListByPage(requestVO.toMap(), page);
            } else {
                if (userInfo.getSourceSys() == 1) { // 主播
                    requestVO.setUserType(1);
                    userIdList = this.userInfoService.selectAnchorIdsByDeptIds(deptIdList);
                } else {
                    userIdList = this.userInfoService.selectSalesmanUserIdsByDeptIds(deptIdList);
                }
                requestVO.setUserIdList(userIdList);
                page = this.spreadLimitService.selectListByPage(requestVO.toMap(), page);
            }
            result = new BaseResponseBody<BasePage<SpreadLimit>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_LIMIT_LIST_SUCCESS.getMsg()), page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<BasePage<SpreadLimit>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_LIMIT_LIST_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 保存信息_新建上限记录功能
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/spreadLimitSave.json", method = RequestMethod.POST)
    @RequiredParams(names = {})
    public BaseResponseBody<SpreadLimit> spreadLimitSave(HttpServletRequest request) {
        BaseResponseBody<SpreadLimit> result = null;
        try {
            // 请求对象
            SpreadLimit spreadLimit = this.getParameterBean(SpreadLimit.class);
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            if (StringUtils.isNotBlank(spreadLimit.getId())) {
                // 把剩余数量一同变化
                SpreadLimit selectLimit = this.spreadLimitService.selectByPrimaryKey(spreadLimit.getId());
                if (selectLimit != null) {
                    // 原数据
                    int remainNum = selectLimit.getRemainNum();
                    int num = selectLimit.getNum();
                    // 传进来
                    int recordNum = spreadLimit.getNum();
                    remainNum = remainNum + (recordNum - num);
                    if (remainNum < 0) {
                        return new BaseResponseBody<SpreadLimit>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_LESS_PROCEED_ERROR.getMsg()), null);
                    }
                    spreadLimit.setRemainNum(remainNum);
                }
                this.spreadLimitService.updateByPrimaryKeySelective(spreadLimit);
            } else {
                // 查询是否已经存在
                if (spreadLimit.getObjId() == null || StringUtils.isEmpty(spreadLimit.getObjId())) { // 新增系统默认
                    SpreadLimit selectByObjId = new SpreadLimit();
                    if (userInfo.getSourceSys() == 1) {
                        selectByObjId = this.spreadLimitService.selectByObjId("-1");//主播
                    } else {
                        selectByObjId = this.spreadLimitService.selectByObjId("-2");//业务员
                    }
                    if (selectByObjId == null) {
                        this.spreadLimitService.insertSelectiveSaveDefault(spreadLimit, userInfo);
                    } else {
                        return new BaseResponseBody<SpreadLimit>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_DEFAULT_DATA_ERROR.getMsg()), null);
                    }
                } else {
                    SpreadLimit selectByObjId = this.spreadLimitService.selectByObjId(spreadLimit.getObjId());
                    if (selectByObjId == null) {
                        this.spreadLimitService.insertSelectiveSave(spreadLimit, userInfo);
                    } else {
                        return new BaseResponseBody<SpreadLimit>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_USER_DATA_ERROR.getMsg()), null);
                    }
                }
            }
            result = new BaseResponseBody<SpreadLimit>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_LIMIT_SAVE_SUCCESS.getMsg()), spreadLimit);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<SpreadLimit>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_LIMIT_SAVE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 批量修改状态
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/limitUpdateState.json", method = RequestMethod.POST)
    @RequiredParams(names = {"ids", "state"})
    public BaseResponseBody<Boolean> limitUpdateState(HttpServletRequest request) {
        BaseResponseBody<Boolean> result = null;
        try {
            // 请求参数
            String[] ids = this.getParameterArray("ids", new String[]{});
            int state = this.getParameterInteger("state", null);
            this.spreadLimitService.updateStateByIds(Arrays.asList(ids), state);
            result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.UPDATE_STATE_IDS_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.UPDATE_STATE_IDS_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 删除信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/spreadLimitDelete.json", method = RequestMethod.POST)
    @RequiredParams(names = {"ids"})
    public BaseResponseBody<Boolean> spreadLimitDelete(HttpServletRequest request) {
        BaseResponseBody<Boolean> result = null;
        try {
            // 请求参数
            String[] ids = this.getParameterArray("ids", new String[]{});

            this.spreadLimitService.deleteByPrimaryKeys(Arrays.asList(ids));
            result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_LIMIT_DELETE_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), TaskResponseMsg.SPREAD_LIMIT_DELETE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 查询所有的子集id
     *
     * @param parentCode
     * @param list
     * @throws Exception
     */
    private void selectDeptSon(String parentCode, List<String> list) throws Exception {
        List<Dept> deptList = this.deptService.selectByParentCode(parentCode);

        if (deptList != null) {
            for (Dept dept1 : deptList) {
                list.add(dept1.getId());
                selectDeptSon(dept1.getCode(), list);
            }
        }
    }

}
